﻿<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>上传文件</title>
</head>
<body>
    选择文件上传：<input id="inputFile" type="file" />
    <br />
    <img id="result" src="/no-image.jpeg" alt="暂无图片" />

    <script src="./signalr.js"></script>
    <script>
        function getObjectURL(file) {
            var url = null;
            if (window.createObjectURL != undefined) {
                url = window.createObjectURL(file)
            } else if (window.URL != undefined) {
                url = window.URL.createObjectURL(file)
            } else if (window.webkitURL != undefined) {
                url = window.webkitURL.createObjectURL(file)
            }
            return url
        };

        const __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
            //debugger
            //console.log(generator);
            return new (P || (P = Promise))(function (resolve, reject) {
                function fulfilled(value) {
                    try {
                        step(generator.next(value));
                    } catch (e) {
                        reject(e);
                    }
                }

                function rejected(value) {
                    try {
                        step(generator["throw"](value));
                    } catch (e) {
                        reject(e);
                    }
                }

                function step(result) {
                    if (result instanceof Promise) {
                        result
                            .then(r => {
                                //debugger
                                r.done ? resolve(r.value) : new P(function (resolve) {
                                    resolve(r.value);
                                }).then(fulfilled, rejected);
                            })
                            .catch(e => reject(e))
                    }
                    else {
                        //debugger
                        result.done ? resolve(result.value) : new P(function (resolve) {
                            resolve(result.value);
                        }).then(fulfilled, rejected);
                    }
                }

                //debugger
                //generator = generator.apply(thisArg, _arguments || []);
                //n = generator.next()
                //step(n);
                step((generator = generator.apply(thisArg, _arguments || [])).next());
            });
        };

        // 链接到自己的hub 初始化 路由：/streaming 被路由节点捕获
        let connection = new signalR.HubConnectionBuilder()
            .withUrl("/streaming")
            .build();
        connection.start().then(() => {
            console.log("已建立链接");
        });

        let resultImg = document.querySelector('#result');
        let inputFile = document.querySelector('#inputFile');

        function getBase64(file) {
            return new Promise((resolve, reject) => {
                let reader = new FileReader();
                let imgResult = "";
                reader.readAsDataURL(file);
                reader.onload = function () {
                    imgResult = reader.result;
                };
                reader.onerror = function (error) {
                    reject(error);
                };
                reader.onloadend = function () {
                    resolve(imgResult);
                };
            });
        }

        inputFile.addEventListener('change', async event => {
            if (event.target.files.length) {
                let file = event.target.files[0];

                const fileType = file.type.substring(
                    file.type.lastIndexOf("/") + 1,
                    file.type.length
                );
                let type =
                    fileType == "jpg" ||
                    fileType == "jpeg" ||
                    fileType == "png" ||
                    fileType == "JPG" ||
                    fileType == "JPEG";
                console.log("type", type);
                if (!type) {
                    console.log("上传图片只能是jpg 、 jpeg 、 png 、 JPG 、 JPEG格式!");
                    return;
                }

                //debugger
                __awaiter(this, void 0, void 0, async function* () {
                    const subject = new signalR.Subject();
                    try {
                        yield connection.send('UploadImage', subject);

                        // 发送文件名
                        let fileName = file.name;
                        subject.next(fileName);
                        //debugger

                        // 发送内容
                        let shardSize = 1024; // 分片大小
                        let shardCount = Math.ceil(file.size / shardSize); // 总分片数

                        for (let i = 0; i < shardCount; i++) {
                            let start = i * shardSize; // 分片开始位置
                            let end = start + shardSize; // 分片结束位置
                            let packet = file.slice(start, end);  // 将文件进行切片

                            //debugger
                            let base64Data = await getBase64(packet);
                            let base64Image = base64Data.split(';base64,')[1];
                            subject.next(base64Image);
                        }
                    } catch (e) {
                        console.error(e);
                        resultImg.src = '/no-image.jpeg';
                        return;
                    }
                    finally {
                        subject.complete();
                    }

                    resultImg.src = getObjectURL(file);
                });
            }
        });
    </script>
</body>
</html>

<!-- http://www.manongjc.com/detail/24-civwrgnuqscbpsp.html -->
<!-- https://blog.csdn.net/qq_40190624/article/details/125309074 -->
<!-- https://pixabay.com/zh/photos/ -->
<!-- http://t.zoukankan.com/lalalagq-p-9959786.html -->
<!-- https://blog.csdn.net/libin_1/article/details/50433863 -->
